﻿namespace WebPacker.Configuration
{
	using System;
	using System.Collections.Generic;
	using System.Xml;
	using NXml.Serialization;
	using NXml.Serialization.Serializers;

	public class PackInfoCollectionSerializer : XmlEnumerableSerializerBase<PackInfo>
	{
		public override bool Accept(Type type)
		{
			return type == typeof(PackInfoCollection);
		}

		public override void Serialize(XmlSerializerContext context, XmlWriter writer, Type valueType, object value)
		{
			throw new NotImplementedException();
		}

		public override object Deserialize(XmlSerializerContext context, XmlReader reader, Type valueType)
		{
			var packInfos = new List<PackInfo>();
			var packInfoCollection = new PackInfoCollection();

			if (reader.HasAttributes)
			{
				var attribute = reader.GetAttribute("monitoring");

				if (attribute != null)
				{
					packInfoCollection.Monitoring = attribute == "true" || attribute == "1";
				}

				packInfoCollection.Source = reader.GetAttribute("source");
				packInfoCollection.VersionGeneratorName = reader.GetAttribute("versionGenerator");
			}

			base.Deserialize(context, reader, valueType, packInfos);

			foreach (var packInfo in packInfos)
			{
				packInfoCollection.Add(packInfo);
			}

			return packInfoCollection;
		}
	}
}
